package com.zj.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.*;
import com.zj.pojo.Apple;
import com.zj.tool.DateTools;
import org.springframework.boot.jackson.JsonComponent;
import org.springframework.boot.jackson.JsonObjectDeserializer;
import org.springframework.boot.jackson.JsonObjectSerializer;

import java.io.IOException;
import java.util.Date;

@JsonComponent
public class AppleJsonComponent {
    //通过继承JsonObjectSerializer和JsonObjectDeserializer直接逐个属性的控制其序列化过程。
    public static class Serializer extends JsonObjectSerializer<Apple> {


        @Override
        protected void serializeObject(Apple value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
            jgen.writeStringField("reg", value.getRegion());
            jgen.writeNumberField("ID", value.getId());
        }

    }

    public static class Deserializer extends JsonObjectDeserializer<Apple> {

        @Override
        protected Apple deserializeObject(JsonParser jsonParser, DeserializationContext context, ObjectCodec codec, JsonNode tree) throws IOException {
            String name = tree.get("region").textValue();
            float weig = tree.get("weight").floatValue();
            Date date = DateTools.toDateTimeFromStr(tree.get("produceDate").textValue());
            JsonNode id = tree.get("id");
            return id == null ? new Apple(name, weig, date) : new Apple(id.asInt(), name, weig, date);
        }

    }
}
